package com.idis.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Ming on 2018/2/4.
 */

/**
 * 图像服务
 */
@Service
public class ImageService{

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    String DBUrl;

    private final String IMAGE="/image";

    private final String IMG_URL="/";

    /**
     * 保存图像
     * @param file 图像文件
     * @param name 文件名
     * @param ext 文件后缀名
     * @return 图像保存后的文件名（eg.15341321312312.png)
     * @throws IOException
     */
    public String savePicture(MultipartFile file,String name,String ext) throws IOException {
        LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.add("image",new InputStreamResource(file.getInputStream()));
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>(map,headers);
        return restTemplate.postForObject(DBUrl+IMAGE+IMG_URL+name+"."+ext,requestEntity,String.class);
    }

    /**
     * 获取图像
     * @param fileName 图像在服务器中的文件名
     * @return 图像的字节集
     * @throws IOException
     */
    public byte[] getPicture(String fileName) throws IOException {
        HttpHeaders headers = new HttpHeaders();
        List list=new ArrayList();
        list.add(MediaType.IMAGE_PNG);
        headers.setAccept(list);
        ResponseEntity<byte[]> response= restTemplate.exchange(DBUrl+IMAGE+IMG_URL+fileName, HttpMethod.GET,new HttpEntity<byte[]>(headers), byte[].class);
        byte[] result=response.getBody();
        return result;
    }

}
